﻿using System;

namespace maimg.helpers
{
    using System.IO;
    using tuimg;
    using tuimg.element;
    using ZXing.Common;

    internal partial class helper
    {
        internal static TuimgGrid convert_grid(BitMatrix matrix, int w)
        {
            var grid = new TuimgGrid(matrix.Width * w, matrix.Height * w);
            for (int i = 0; i < matrix.Height; i++) for (var j = 0; j < matrix.Width; j++) if (matrix[j, i]) for (var k = 0; k < w; k++) for (var k2 = 0; k2 < w; k2++) grid.On(j * w + k, i * w + k2);

            grid = grid.CopyTrim();
            var g = new TuimgGrid(grid.Width + 20, grid.Height + 20);
            g.Cross(grid, 10, 10);
            return g;
        }
        internal static TuimgGrid grid_add_text(TuimgGrid grid, string content, string fontpath)
        {
            grid = grid.CopyTrim();
            var g = new TuimgGrid(grid.Width + 20, grid.Height + 60);
            g.Cross(grid, 10, 10);
            using (var font = new TuimgFont(fontpath))
            {
                var gtext = new TuimgGrid(900, 60);
                var x = 0;
                foreach (var i in content)
                {
                    if (i != ' ')
                    {
                        var gchar = font.ReadPath(i).ToGrid_ScaleHeight(35);
                        gtext.Cross(gchar, x, gtext.Height - gchar.Height);
                        x += gchar.Width;
                    }
                    x += 6;
                }
                g.Cross(gtext.CopyTrim(), 10, g.Height - 45);
            }
            return grid;
        }

        internal static Stream download_png(TuimgGrid g)
        {
            using (var img = new TuimgPng(g.Width, g.Height))
            {
                img.DrawGrid(0, 0, g, TuimgColor.Black);
                return img.ToStream();
            }
        }
        internal static Stream download_bmp(TuimgGrid g)
        {
            using (var img = new TuimgBmp(g.Width, g.Height)){
                img.DrawGrid(0, 0, g, TuimgColor.Black);
                return img.ToStream();
            }
        }

        internal static Stream download_bmp(BitMatrix matrix, int w)
        {
            return helper.download_bmp(helper.convert_grid(matrix, w));
        }
        internal static Stream download_png(BitMatrix matrix, int w)
        {
            return helper.download_png(helper.convert_grid(matrix, w));
        }
    }
}
